package com.zmn.oms.business.impl.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.base.channel.common.dro.ChannelDRO;
import com.zmn.base.channel.dubbo.interfaces.channel.ChannelListRemoteService;
import com.zmn.base.pilot.common.dto.pilot.PilotCheckQuery;
import com.zmn.base.pilot.common.enums.PilotTypeEnum;
import com.zmn.base.pilot.dubbo.interfaces.pilot.PilotRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.categ.CategProductEcErpDRO;
import com.zmn.base.product.common.dto.categ.CategProductGroupDRO;
import com.zmn.base.product.common.dto.categ.CategServDRO;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.DefaultEcProductQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.common.query.categ.CategProductEcErpQuery;
import com.zmn.base.product.common.query.categ.CategProductGroupQuery;
import com.zmn.base.product.dubbo.interfaces.categ.CategProductEcErpListRemoteService;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServListRemoteService;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServProductListRemoteService;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.business.interfaces.order.SimpleOrderBService;
import com.zmn.oms.business.interfaces.product.OrderProductExtendBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.business.interfaces.work.OrderWorkBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.FilterUtil;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.order.OmsProductDTO;
import com.zmn.oms.model.dto.order.OrderDTO;
import com.zmn.oms.model.dto.order.ServProductDTO;
import com.zmn.oms.model.dto.work.modify.BackProductPriceQueryDTO;
import com.zmn.oms.model.dto.work.modify.BackProductPriceResultDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.factory.OrderFactory;
import com.zmn.oms.model.entity.order.Order;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.operation.OrderOperationService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.outermap.OrderOuterMapService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.shop.OrderShopService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.ums.common.constant.UserConsts;
import com.zmn.uuc.common.dio.user.UserTempRegisterDIO;
import com.zmn.uuc.common.dro.user.UserDetailDRO;
import com.zmn.uuc.dubbo.interfaces.user.UserRegisterRemoteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author sunlife
 * @date:2020/7/3 2:58 下午
 * description:
 */
@Service("simpleOrderBService")
public class SimpleOrderBServiceImpl implements SimpleOrderBService {
    private Logger logger = LoggerFactory.getLogger(OrderBServiceImpl.class);
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private com.zmn.uuc.dubbo.interfaces.user.UserListRemoteService userListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserRegisterRemoteService userRegisterRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private ChannelListRemoteService channelListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private CategProductEcErpListRemoteService categProductEcErpListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private ProductForeignListRemoteService productForeignListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private CategServListRemoteService categServListRemoteService;
    @Reference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    private CategServProductListRemoteService categServProductListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private PilotRemoteService pilotRemoteService;

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderWorkBService orderWorkBService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderWarrantyService orderWarrantyService;
    @Autowired
    private OrderCommentService orderCommentService;
    @Autowired
    private OrderOuterMapService orderOuterMapService;
    @Autowired
    private OrderFactoryService orderFactoryService;
    @Autowired
    private OrderProductExtendBService orderProductExtendBService;
    @Autowired
    private OrderShopService orderShopService;
    @Autowired
    private OrderServiceItemService orderServiceItemService;
    @Autowired
    private OrderOperationService orderOperationService;
    @Autowired
    OrderMemberService orderMemberService;
    @Autowired
    private ServItemBService servItemBService;


    @Override
    public void processOrder(OrderDTO orderDTO) throws OmsBaseException {
        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();

        // 默认新单
        order.setType(Optional.ofNullable(order.getType()).orElse(OrderConsts.ORDER_TYPE_NEW));

        // 默认服务商/公司
        order.setCompanyId(Optional.ofNullable(order.getCompanyId()).orElse(GlobalConsts.NONE));
        order.setOrgOneId(Optional.ofNullable(order.getOrgOneId()).orElse(GlobalConsts.NONE));
        order.setOrgTwoId(Optional.ofNullable(order.getOrgTwoId()).orElse(GlobalConsts.NONE));
        order.setOrgThreeId(Optional.ofNullable(order.getOrgThreeId()).orElse(GlobalConsts.NONE));
        order.setOrgFourId(Optional.ofNullable(order.getOrgFourId()).orElse(GlobalConsts.NONE));

        // 订单处理
        this.processOrder(order, orderDetail, orderDTO.getOrderWork().getChannelId(), orderDTO.getOperator(), orderDTO.getOperatorId());

        // 订单产品处理
        this.processOrderProductList(orderDTO);

        // 订单详情处理
        this.processOrderDetail(orderDTO);

        // 订单扩展信息处理
        this.processOrderExtend(orderDTO);
    }

    /**
     * 订单处理
     *
     * @param order       订单
     * @param orderDetail 订单详情
     * @param channelId   渠道ID
     * @throws OmsBaseException
     */
    private void processOrder(Order order, OrderDetail orderDetail, Integer channelId, String operator, Long operatorId) {

        // 过滤空格
        orderDetail.setTelephone(orderDetail.getTelephone().trim());
        orderDetail.setTelephone2(StringUtils.defaultString(orderDetail.getTelephone2()).trim());
        orderDetail.setTelephone3(StringUtils.defaultString(orderDetail.getTelephone3()).trim());

        // region 用户处理
        if (NumberUtil.isNullOrZero(order.getUserId())) {
            // 未登录状态创建临时用户
            UserTempRegisterDIO userTempRegisterDIO = new UserTempRegisterDIO();
            userTempRegisterDIO.setGender(orderDetail.getGender());
            userTempRegisterDIO.setPlat(order.getPlat());
            userTempRegisterDIO.setChannelId(channelId);
            userTempRegisterDIO.setNickName(FilterUtil.replaceSpeChar(StringUtils.defaultString(orderDetail.getUserName())));
            userTempRegisterDIO.setEntrance(order.getReceiveEntranceId());
            userTempRegisterDIO.setOperatorId(operatorId);
            userTempRegisterDIO.setOperator(operator);
            ResponseDTO<ChannelDRO> channelResponseDTO = channelListRemoteService.getByChannelId(channelId);
            if(channelResponseDTO.isSuccess() && channelResponseDTO.getData() != null){
                userTempRegisterDIO.setChannelName(channelResponseDTO.getData().getName());
            }
            logger.debug("厂商批量下单调用uuc创建临时用户入参，userRegisterDIO：{}", JSONObject.toJSONString(userTempRegisterDIO.toString()));
            ResponseDTO<Long> userResponseDTO = userRegisterRemoteService.registerTempUser(userTempRegisterDIO);
            logger.debug("厂商批量下单调用uuc创建临时用户出参，userResponseDTO：{}，orderId：{}", JSONObject.toJSONString(userResponseDTO),order.getOrderId());
            if (userResponseDTO.getData() != null) {
                order.setUserId(userResponseDTO.getData());
            } else {
                logger.error("调用uuc创建临时用户失败，手机号：{}，失败原因：{}", orderDetail.getTelephone(), userResponseDTO.getMessage());
            }
        } else {
            Integer vvip = GlobalConsts.NO;
            Integer userType = Optional.ofNullable(orderDetail.getUserType()).orElse(UserConsts.USER_TYPE_ORDINARY);
            if (Objects.equals(userType, UserConsts.USER_TYPE_ORDINARY)) {
                // uuc 查询个人用户信息
                ResponseDTO<UserDetailDRO> userResponseDTO = userListRemoteService.getUserDetailById(order.getUserId(), false);
                if (userResponseDTO.getData() != null) {
                    vvip = userResponseDTO.getData().getVvip();
                }
            } else {
                // ums查询用户信息
                ResponseDTO<UserDetailDRO> userResponseDTO = userListRemoteService.getUserById(order.getUserId(), false);
                if (userResponseDTO.getData() != null) {
                    vvip = userResponseDTO.getData().getVvip();
                }
            }
            orderDetail.setVvip(vvip);
        }

        order.setUserId(Optional.ofNullable(order.getUserId()).orElse((long) GlobalConsts.NONE));
        orderDetail.setUserType(Optional.ofNullable(orderDetail.getUserType()).orElse(UserConsts.USER_TYPE_ORDINARY));
        orderDetail.setVvip(Optional.ofNullable(orderDetail.getVvip()).orElse(GlobalConsts.NO));
        // endregion

        // 判断经纬度，判断是否在这个城市下面，如果不在这个城市，则塞城市下的第一个区，经纬度清空，标准地址塞到详细地址里
        orderDetail.setStreet(StringUtils.defaultString(orderDetail.getStreet()));
        if (orderDetail.getCountyId() == null) {
            order.setNaturalCityId(order.getCityId());
            orderDetail.setCountyId(GlobalConsts.NONE);
            orderDetail.setCountyName("");
            orderDetail.setLatitude(null);
            orderDetail.setLongitude(null);
            orderDetail.setAddress(String.format("%s %s", orderDetail.getStreet(), StringUtils.defaultString(orderDetail.getAddress())));
            orderDetail.setStreet("");
        }
    }

    /**
     * 订单详情数据处理
     *
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderDetail(OrderDTO orderDTO) throws OmsBaseException {
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        orderDetail.setUserName(FilterUtil.replaceSpeChar(orderDetail.getUserName()));// 用户名替换特殊符号
        orderDetail.setContactName(FilterUtil.replaceSpeChar(StringUtils.defaultString(orderDetail.getContactName(), orderDetail.getUserName())));
        orderDetail.setGender(Optional.ofNullable(orderDetail.getGender()).orElse(GlobalDict.GENDER_NO));
        orderDetail.setNaturalCityName(orderDetail.getCityName());
        orderDetail.setStreetSource(Optional.ofNullable(orderDetail.getStreetSource()).orElse(0));
        orderDetail.setStreetId(Optional.ofNullable(orderDetail.getStreetId()).orElse(0));
        if (StringUtil.isBlank(orderDetail.getStreet())) {
            orderDetail.setStreet(orderDetail.getCountyName());
        }
    }

    /**
     * 订单扩展数据处理
     *
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderExtend(OrderDTO orderDTO) throws OmsBaseException {
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderProduct orderProduct = orderDTO.getOrderProductList().get(0);

        // 三日无忧退
        OrderExtend orderExtend = Optional.ofNullable(orderDTO.getOrderExtend()).orElse(new OrderExtend());
        logger.info("获取当前工单是否是三日无忧退工单 入参：channelId: {}, cityId:{}, servCategId:{}, categId:{}", orderWork.getChannelId(), orderWork.getCityId(), orderWork.getServCategId(), orderProduct.getShowCategId());
        PilotCheckQuery query = new PilotCheckQuery();
        query.setChannelId(orderWork.getChannelId());
        query.setCityId(orderWork.getCityId());
        query.setServCategId(orderWork.getServCategId());
        query.setCategId(orderProduct.getShowCategId());
        query.setPilotTypeId(PilotTypeEnum.THREE_DAY_RETREAT.getId());
        ResponseDTO<Boolean> responseDTO = pilotRemoteService.checkPilotByQuery(query);
        logger.info("获取当前工单是否是三日无忧退工单 出参：{}", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            logger.info("无法获取当前工单是否是三日无忧退工单，入参：channelId: {}, cityId:{}, servCategId:{}, categId:{}, 原因:{}", orderWork.getChannelId(), orderWork.getCityId(), orderWork.getServCategId(), orderProduct.getShowCategId(), responseDTO.getMessage());
        } else {
            orderExtend.setAllowRefund(responseDTO.getData() ? GlobalConsts.YES : GlobalConsts.NO);
        }
        orderDTO.setOrderExtend(orderExtend);
    }
    /**
     * 订单产品处理
     *
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderProductList(OrderDTO orderDTO) throws OmsBaseException {
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        OrderWork orderWork = orderDTO.getOrderWork();
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();
        if (CollectionUtils.isEmpty(orderProductList)) {
            return;
        }

        // 目前就一个产品
        OrderProduct orderProduct = orderProductList.get(0);
        orderProduct.setNumber(Optional.ofNullable(orderProduct.getNumber()).orElse(1));

        OmsProductDTO omsProductDTO = this.processProduct(orderWork, orderProduct.getShowProductId(), orderProduct.getProductId(), orderProduct.getBrandId());
        // 后端产品
        ServProductDTO product = omsProductDTO.getProduct();
        orderProduct.setCategOneId(product.getCategOneId());
        orderProduct.setCategOneName(product.getCategOneName());
        orderProduct.setCategId(product.getCategId());
        orderProduct.setCategName(product.getCategName());
        orderProduct.setProductId(product.getProductId());
        orderProduct.setProductName(product.getProductName());
        orderProduct.setProductUnit(StringUtils.defaultString(product.getProductUnit()));
        // 前端产品
        ServProductDTO showProduct = omsProductDTO.getShowProduct();
        orderProduct.setShowCategOneId(showProduct.getCategOneId());
        orderProduct.setShowCategOneName(showProduct.getCategOneName());
        orderProduct.setShowCategId(showProduct.getCategId());
        orderProduct.setShowCategName(showProduct.getCategName());
        orderProduct.setShowProductId(showProduct.getProductId());
        orderProduct.setShowProductName(showProduct.getProductName());
        orderProduct.setShowProductUnit(StringUtils.defaultString(showProduct.getProductUnit()));

        // 自带服务项订单无需查询计算原价
        boolean isNotQuotationOrder = !Objects.equals(OrderConsts.SERVICE_ITEM_TYPE_FAULT, orderDTO.getOriginServItemType());

        orderProduct.setBrandId(Optional.ofNullable(orderProduct.getBrandId()).orElse(GlobalConsts.NONE));
        orderProduct.setBrandName(StringUtils.defaultString(orderProduct.getBrandName()));

        // 设置原价
/*        if (orderProduct.getPrice() != null) {
            order.setOriginalAmount(orderProduct.getPrice() * orderProduct.getNumber());
        }*/

        // 服务分类
        orderDetail.setServCategId(omsProductDTO.getServCategId());
        orderDetail.setServCategName(product.getServCategName());
        orderDetail.setCategOneId(product.getCategOneId());
        orderDetail.setCategId(product.getCategId());
        orderDetail.setProductId(product.getProductId());
        orderDetail.setProductInfo(String.format("%s-%s*%s", StringUtils.defaultString(orderProduct.getBrandName()), omsProductDTO.getProductName(), orderProduct.getNumber()));
        // 产品分组
        orderDetail.setProductGroupId(product.getProductGroupId());
        orderDetail.setProductGroupName(product.getProductGroupName());
        // 冗余到工单
        orderWork.setShowServCategName(showProduct.getServCategName());
        orderWork.setShowProductGroupId(showProduct.getProductGroupId());
        orderWork.setShowProductGroupName(showProduct.getProductGroupName());

        if (NumberUtil.isNotNullOrZero(product.getCategId())) {
            // 后台产品分组
            logger.info("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 入参：servCateg={}, categTwoId={}", omsProductDTO.getServCategId(), product.getCategId());
            CategProductGroupQuery query = new CategProductGroupQuery();
            query.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
            query.setServCategId(omsProductDTO.getServCategId());
            query.setCategId(product.getCategId());
            query.setBizType(orderWork.getBizType());
            ResponseDTO<CategProductGroupDRO> categoryProductGroupDROResponseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(query);
            logger.info("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 出参：【{}】", categoryProductGroupDROResponseDTO);
            CategProductGroupDRO categorySimpleProductGroupDRO = categoryProductGroupDROResponseDTO.getData();
            if (categorySimpleProductGroupDRO != null) {
                orderWork.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
                orderWork.setServProductGroupName(categorySimpleProductGroupDRO.getName());
                orderWork.setBizLine(categorySimpleProductGroupDRO.getBizLine());
            }
        }
    }

    /**
     * 处理产品
     *
     * @param showProductId 前端产品
     * @param productId     后端产品
     */
    //TODO 待优化
    private OmsProductDTO processProduct(OrderWork orderWork, Integer showProductId, Integer productId, Integer brandId) throws OmsBaseException {
        if (NumberUtil.isNullOrZero(showProductId) && NumberUtil.isNullOrZero(productId)) {
            throw new OmsBaseException("产品不存在");
        }

        OmsProductDTO omsProductDTO = new OmsProductDTO();

        ProductBaseDRO productBaseDRO = null;
        Integer realProductId = null;
        boolean isShowProduct = false;

        // 有后端产品ID，通过后端产品ID查找
        if (!NumberUtil.isNullOrZero(productId)) {
            ProductBaseQuery productDIO = new ProductBaseQuery();
            productDIO.setProductId(productId);
            com.zmn.common.dto2.ResponseDTO<List<ProductBaseDRO>> productDROResp
                    = productForeignListRemoteService.listBaseDROByQuery(productDIO);
            List<ProductBaseDRO> productDROS = productDROResp.getData();
            if (CollectionUtil.isNotNullOrEmpty(productDROS)) {
                productBaseDRO = productDROS.get(0);
                realProductId = productId;
                isShowProduct = Objects.equals(GlobalConsts.YES, productBaseDRO.getShowType());
            }
        }
        // 没有后端产品ID，使用前端产品ID查找
        if (productBaseDRO == null) {
            ProductBaseQuery productDIO = new ProductBaseQuery();
            productDIO.setProductId(showProductId);
            com.zmn.common.dto2.ResponseDTO<List<ProductBaseDRO>> productDROResp
                    = productForeignListRemoteService.listBaseDROByQuery(productDIO);
            List<ProductBaseDRO> productDROS = productDROResp.getData();
            if (CollectionUtil.isNotNullOrEmpty(productDROS)) {
                productBaseDRO = productDROS.get(0);
                realProductId = showProductId;
                isShowProduct = Objects.equals(GlobalConsts.YES, productBaseDRO.getShowType());
            }
        }
        if (productBaseDRO == null) {
            throw new OmsBaseException(String.format("未找到对应的产品 productId=[%d], showProductId=[%d]",
                    productId, showProductId));
        }

        omsProductDTO.setProductName(productBaseDRO.getProductName());
        omsProductDTO.setServCategId(productBaseDRO.getServCategId());

        // 前端产品查后端产品
        if (isShowProduct) {
            // 查询前台产品对应后台产品
            BackProductPriceQueryDTO backProductPriceQueryDTO = BackProductPriceQueryDTO
                    .builder()
                    .showProductId(realProductId)
                    .bizType(orderWork.getBizType())
                    .brandId(brandId)
                    .channelId(orderWork.getChannelId())
                    .cityId(orderWork.getCityId())
                    .platWork(orderWork.getPlatWork())
                    .build();
            BackProductPriceResultDTO backProductPriceResultDTO = servItemBService.queryBackProductPrice(backProductPriceQueryDTO);

            // 前端产品只映射一个后端产品，赋值后端产品
            if (Objects.nonNull(backProductPriceResultDTO)) {

                ProductBaseQuery productDIO = new ProductBaseQuery();
                productDIO.setProductId(backProductPriceResultDTO.getProductId());
                com.zmn.common.dto2.ResponseDTO<List<ProductBaseDRO>> productDROResp
                        = productForeignListRemoteService.listBaseDROByQuery(productDIO);
                List<ProductBaseDRO> productDROS = productDROResp.getData();

                ProductBaseDRO servProductDRO = productDROS.get(0);
                omsProductDTO.setProductName(servProductDRO.getProductName());
                omsProductDTO.setServCategId(servProductDRO.getServCategId());
                omsProductDTO.setProduct(this.droToServProductDTO(servProductDRO));
            } else {
                // 映射多个后台产品，不设置后台产品，仅设置后台产品一级分类
                CategProductEcErpQuery categProductEcErpQuery = new CategProductEcErpQuery();
                categProductEcErpQuery.setEcServCategId(productBaseDRO.getServCategId());
                categProductEcErpQuery.setEcCategOneId(productBaseDRO.getCategOneId());
                categProductEcErpQuery.setEcCategId(productBaseDRO.getCategId());

                ServProductDTO emptyProduct = new ServProductDTO();
                com.zmn.common.dto2.ResponseDTO<List<CategProductEcErpDRO>> categoryRemote =
                        categProductEcErpListRemoteService.listByQuery(categProductEcErpQuery);
                List<CategProductEcErpDRO> categoryItems = categoryRemote.getData();
                if (!CollectionUtils.isEmpty(categoryItems)) {
                    // 设置后台产品一级分类
                    CategProductEcErpDRO showCategoryAssociationDRO = categoryItems.get(0);
                    emptyProduct.setServCategName(showCategoryAssociationDRO.getErpServCategName());
                    emptyProduct.setCategOneId(showCategoryAssociationDRO.getErpCategOneId());
                    emptyProduct.setCategOneName(showCategoryAssociationDRO.getErpCategOneName());
                    logger.debug("设置后台产品一级分类");
                } else {
                    com.zmn.common.dto2.ResponseDTO<CategServDRO> servCategoryRemote = categServListRemoteService.getByServCategId(omsProductDTO.getServCategId());
                    emptyProduct.setServCategName(servCategoryRemote.getData() != null ? servCategoryRemote.getData().getServCategName() : "");
                    emptyProduct.setCategOneId(0);
                    emptyProduct.setCategOneName("");
                    logger.debug("remote无后台产品二级分类数据，只设置服务分类名称");
                }
                emptyProduct.setCategId(0);
                emptyProduct.setCategName("");
                emptyProduct.setProductId(0);
                emptyProduct.setProductName("");
                emptyProduct.setProductUnit("");
                emptyProduct.setProductGroupId(0);
                emptyProduct.setProductGroupName("");
                omsProductDTO.setProduct(emptyProduct);
            }

            omsProductDTO.setShowProduct(this.droToServProductDTO(productBaseDRO));
        }
        // 后端产品查前端产品
        else {
            DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
            defaultEcProductQuery.setProductIdList(Lists.newArrayList(realProductId));
            defaultEcProductQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);

            com.zmn.common.dto2.ResponseDTO<List<ProductBaseDRO>> listResponseDTO =
                    productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
            List<ProductBaseDRO> list = listResponseDTO.getData();
            if (CollectionUtils.isEmpty(list)) {
                throw new OmsBaseException("产品数据配置有误，[" + realProductId + "]没有映射前端产品");
            }

            omsProductDTO.setProduct(this.droToServProductDTO(productBaseDRO));
            omsProductDTO.setShowProduct(this.droToServProductDTO(list.get(0)));
        }

        logger.info("产品信息 OmsProductDTO=[{}]", JSON.toJSONString(omsProductDTO));
        return omsProductDTO;
    }

    private ServProductDTO droToServProductDTO(ProductBaseDRO productBaseDRO) {
        ServProductDTO servProductDTO = BeanMapper.map(productBaseDRO, ServProductDTO.class);
        servProductDTO.setProductName(productBaseDRO.getProductName());
        servProductDTO.setProductUnit(productBaseDRO.getUnit());
        servProductDTO.setProductGroupId(productBaseDRO.getFicoCategId());
        servProductDTO.setProductGroupName(productBaseDRO.getFicoCategName());
        return servProductDTO;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderBO insertOrder(OrderDTO orderDTO) {

        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();
        OrderWork orderWork = orderDTO.getOrderWork();

        // 保存订单详情 订单 订单产品
        orderService.insertOrderAndProduct(orderDTO);

        // 处理啄木鸟预付
        processPrepayAmount(orderDTO);

        // 保存工单
        orderWork.setOrderId(order.getOrderId());
        orderWork.setWorkId(order.getOrderId());
        orderWork.setCreater(order.getCreater());
        orderWork.setCreateTime(order.getCreateTime());

        // 添加工单
        orderWorkBService.insertOrderWork(orderWork);

        // 保存厂商单信息
        OrderFactory orderFactory = orderDTO.getOrderFactory();
        if (orderFactory != null) {
            orderFactory.setFcOrderId(orderWork.getOrderId());
            orderFactoryService.insertOrderFactory(orderDTO.getOrderFactory());
        }

        OrderBO orderBO = new OrderBO();
        orderBO.setOrder(order);
        orderBO.setOrderDetail(orderDetail);
        orderBO.setOrderProductList(orderProductList);
        orderBO.setOrderWork(orderWork);
        return orderBO;
    }
    /**
     * 处理啄木鸟预付
     * @param orderDTO
     */
    private void processPrepayAmount(OrderDTO orderDTO) {
        OrderWork orderWork = orderDTO.getOrderWork();
        List<OrderServiceItem> orderServiceItemList = orderDTO.getOrderServiceItemList();

        // 有服务项 & 一口价的为啄木鸟预付
        boolean haveFinalPrice = CollectionUtils.isNotEmpty(orderServiceItemList) && Objects.equals(orderDTO.getFinalPrice(), GlobalConsts.YES);
        // 需要预付金
        boolean needPrepayAmount = !NumberUtil.isNullOrZero(orderWork.getPrepayAmount());
        // 先付
        if (Objects.equals(orderDTO.getPayType(), GlobalConsts.NO) && (haveFinalPrice || needPrepayAmount)) {
            Integer prepayAmount = null;
            Integer masterAmount = null;
            if (needPrepayAmount && haveFinalPrice) {
                prepayAmount = orderWork.getPrepayAmount();
                // 有预付金的一口价，需要设置工程师收款金额
                masterAmount = MathUtil.sub(orderWork.getOriginalAmount(), Optional.ofNullable(orderWork.getDiscountAmount()).orElse(0));
                masterAmount = MathUtil.sub(masterAmount, prepayAmount);
            } else if (needPrepayAmount) {
                // 只需付预付金
                prepayAmount = orderWork.getPrepayAmount();
            } else if (haveFinalPrice) {
                // 只一口价
                prepayAmount = MathUtil.sub(orderWork.getOriginalAmount(), Optional.ofNullable(orderWork.getDiscountAmount()).orElse(0));
            }

            orderWork.setPrepayAmount(prepayAmount);
            if (Objects.equals(0, prepayAmount)) {
                orderWork.setPrepayStatus(PayConsts.PAY_STATUS_DONE);
                orderWork.setDisableDiscard(GlobalConsts.NO);
            } else {
                orderWork.setPrepayStatus(PayConsts.PAY_STATUS_ING);
                orderWork.setDisableDiscard(GlobalConsts.YES);
            }
            orderWork.setMasterAmount(masterAmount);
        }else {
            orderWork.setPrepayStatus(GlobalConsts.NONE);
        }
    }
}